using System;
using System.Collections.Generic;
using System.Linq;
using netDxf;
using netDxf.Entities;
using netDxf.Tables;
using netDxf.Collections;
using Point = netDxf.Entities.Point;
using Line = netDxf.Entities.Line;
using Ellipse = netDxf.Entities.Ellipse;
using Arc = netDxf.Entities.Arc;
using Polyline = netDxf.Entities.MLine;
using Text = netDxf.Entities.Text;
using MText = netDxf.Entities.MText;

namespace CPlatePrintSys.Annotation.Converters
{
    /// <summary>
    /// 镜像方向枚举
    /// </summary>
    public enum MirrorDirection
    {
        Horizontal,  // 水平镜像
        Vertical    // 垂直镜像
    }

    /// <summary>
    /// 镜像操作结果，包含文档和实体映射关系
    /// </summary>
    public class MirrorResult
    {
        /// <summary>
        /// 镜像后的DXF文档
        /// </summary>
        public DxfDocument MirroredDocument { get; set; }
        
        /// <summary>
        /// Handle映射关系：原始Handle -> 镜像Handle
        /// </summary>
        public Dictionary<string, string> HandleMapping { get; set; }
        
        /// <summary>
        /// 实体映射关系：原始Handle -> 镜像实体
        /// </summary>
        public Dictionary<string, EntityObject> EntityMapping { get; set; }
        
        /// <summary>
        /// 镜像方向
        /// </summary>
        public MirrorDirection Direction { get; set; }
        
        /// <summary>
        /// 镜像线信息
        /// </summary>
        public MirrorLineInfo MirrorLine { get; set; }
        
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedTime { get; set; }
        
        /// <summary>
        /// 文档名称
        /// </summary>
        public string DocumentName { get; set; }
        
        public MirrorResult()
        {
            HandleMapping = new Dictionary<string, string>();
            EntityMapping = new Dictionary<string, EntityObject>();
            CreatedTime = DateTime.Now;
        }
    }

    /// <summary>
    /// 镜像线信息
    /// </summary>
    public class MirrorLineInfo
    {
        public Vector2 StartPoint { get; set; }
        public Vector2 EndPoint { get; set; }
        public MirrorDirection Direction { get; set; }
        
        public MirrorLineInfo(Vector2 start, Vector2 end, MirrorDirection direction)
        {
            StartPoint = start;
            EndPoint = end;
            Direction = direction;
        }
    }

    /// <summary>
    /// 镜像实体映射管理器，用于维护实体的镜像关系
    /// </summary>
    public class MirrorEntityMappingManager
    {
        private static readonly Dictionary<string, MirrorResult> _mirrorResults = new Dictionary<string, MirrorResult>();
        private static readonly Dictionary<string, Dictionary<string, string>> _globalHandleMapping = new Dictionary<string, Dictionary<string, string>>();
        private static readonly Dictionary<string, Dictionary<string, string>> _globalReverseHandleMapping = new Dictionary<string, Dictionary<string, string>>();
        
        /// <summary>
        /// 注册镜像结果
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="mirrorResult">镜像结果</param>
        public static void RegisterMirrorResult(string documentName, MirrorResult mirrorResult)
        {
            if (string.IsNullOrEmpty(documentName) || mirrorResult == null)
                return;
                
            _mirrorResults[documentName] = mirrorResult;
            
            // 建立全局Handle映射
            if (!_globalHandleMapping.ContainsKey(documentName))
                _globalHandleMapping[documentName] = new Dictionary<string, string>();
            if (!_globalReverseHandleMapping.ContainsKey(documentName))
                _globalReverseHandleMapping[documentName] = new Dictionary<string, string>();
                
            // 关键修复：根据文档类型建立不同的映射关系
            // 原始文档：只存储 原始Handle -> 镜像Handle 的映射
            // 镜像文档：只存储 镜像Handle -> 原始Handle 的映射
            bool isMirroredDocument = documentName.Contains("_Mirrored");
            
            foreach (var mapping in mirrorResult.HandleMapping)
            {
                string originalHandle = mapping.Key;    // 原始Handle
                string mirroredHandle = mapping.Value;  // 镜像Handle
                
                if (isMirroredDocument)
                {
                    // 镜像文档：只存储 镜像Handle -> 原始Handle 的映射
                    _globalHandleMapping[documentName][mirroredHandle] = originalHandle;
                    _globalReverseHandleMapping[documentName][originalHandle] = mirroredHandle;
                    
                    //System.Diagnostics.Debug.WriteLine($"镜像文档映射: {mirroredHandle} -> {originalHandle}");
                    //System.Diagnostics.Debug.WriteLine($"镜像文档反向映射: {originalHandle} -> {mirroredHandle}");
                }
                else
                {
                    // 原始文档：只存储 原始Handle -> 镜像Handle 的映射
                    _globalHandleMapping[documentName][originalHandle] = mirroredHandle;
                    _globalReverseHandleMapping[documentName][mirroredHandle] = originalHandle;
                    
                    //System.Diagnostics.Debug.WriteLine($"原始文档映射: {originalHandle} -> {mirroredHandle}");
                    //System.Diagnostics.Debug.WriteLine($"原始文档反向映射: {mirroredHandle} -> {originalHandle}");
                }
            }
            
            // 关键修复：为原始文档也建立映射关系
            if (isMirroredDocument)
            {
                // 如果这是镜像文档，为原始文档也建立映射
                string originalDocumentName = documentName.Replace("_Mirrored", "");
                
                if (!_globalHandleMapping.ContainsKey(originalDocumentName))
                    _globalHandleMapping[originalDocumentName] = new Dictionary<string, string>();
                if (!_globalReverseHandleMapping.ContainsKey(originalDocumentName))
                    _globalReverseHandleMapping[originalDocumentName] = new Dictionary<string, string>();
                
                foreach (var mapping in mirrorResult.HandleMapping)
                {
                    string originalHandle = mapping.Key;    // 原始Handle
                    string mirroredHandle = mapping.Value;  // 镜像Handle
                    
                    // 原始文档：存储 原始Handle -> 镜像Handle 的映射
                    _globalHandleMapping[originalDocumentName][originalHandle] = mirroredHandle;
                    _globalReverseHandleMapping[originalDocumentName][mirroredHandle] = originalHandle;
                    
                    //System.Diagnostics.Debug.WriteLine($"为原始文档建立映射: {originalHandle} -> {mirroredHandle}");
                    //System.Diagnostics.Debug.WriteLine($"为原始文档建立反向映射: {mirroredHandle} -> {originalHandle}");
                }
                
                System.Diagnostics.Debug.WriteLine($"为原始文档 {originalDocumentName} 建立了 {mirrorResult.HandleMapping.Count} 个映射");
            }
            
            //System.Diagnostics.Debug.WriteLine($"镜像映射管理器: 注册文档 {documentName}，映射数量: {mirrorResult.HandleMapping.Count}");
            //System.Diagnostics.Debug.WriteLine($"文档类型: {(isMirroredDocument ? "镜像文档" : "原始文档")}");
            //System.Diagnostics.Debug.WriteLine($"映射策略: {(isMirroredDocument ? "镜像Handle -> 原始Handle" : "原始Handle -> 镜像Handle")}");
            
            // 调试：显示所有文档的映射统计
            var stats = GetMappingStatistics();
            System.Diagnostics.Debug.WriteLine($"当前所有文档映射统计:");
            foreach (var stat in stats)
            {
                System.Diagnostics.Debug.WriteLine($"  文档 {stat.Key}: {stat.Value} 个映射");
            }
        }
        
        /// <summary>
        /// 获取镜像Handle
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="originalHandle">原始Handle</param>
        /// <returns>镜像Handle，如果不存在则返回null</returns>
        public static string GetMirroredHandle(string documentName, string originalHandle)
        {
            if (string.IsNullOrEmpty(documentName) || string.IsNullOrEmpty(originalHandle))
                return null;
                
            // 关键修复：根据文档类型进行正确的查询
            bool isMirroredDocument = documentName.Contains("_Mirrored");
            
            if (isMirroredDocument)
            {
                // 镜像文档：查询 镜像Handle -> 原始Handle 的映射
                if (_globalReverseHandleMapping.ContainsKey(documentName) && 
                    _globalReverseHandleMapping[documentName].ContainsKey(originalHandle))
                {
                    var result = _globalReverseHandleMapping[documentName][originalHandle];
                    System.Diagnostics.Debug.WriteLine($"镜像文档查询镜像Handle: {originalHandle} -> {result}");
                    return result;
                }
            }
            else
            {
                // 原始文档：查询 原始Handle -> 镜像Handle 的映射
                if (_globalHandleMapping.ContainsKey(documentName) && 
                    _globalHandleMapping[documentName].ContainsKey(originalHandle))
                {
                    var result = _globalHandleMapping[documentName][originalHandle];
                    System.Diagnostics.Debug.WriteLine($"原始文档查询镜像Handle: {originalHandle} -> {result}");
                    return result;
                }
            }
            
            return null;
        }
        
        /// <summary>
        /// 获取原始Handle
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="mirroredHandle">镜像Handle</param>
        /// <returns>原始Handle，如果不存在则返回null</returns>
        public static string GetOriginalHandle(string documentName, string mirroredHandle)
        {
            if (string.IsNullOrEmpty(documentName) || string.IsNullOrEmpty(mirroredHandle))
                return null;
                
            // 关键修复：根据文档类型进行正确的查询
            bool isMirroredDocument = documentName.Contains("_Mirrored");
            
            if (isMirroredDocument)
            {
                // 镜像文档：查询 镜像Handle -> 原始Handle 的映射
                if (_globalReverseHandleMapping.ContainsKey(documentName) &&
                    _globalReverseHandleMapping[documentName].ContainsKey(mirroredHandle))
                {
                    var result = _globalReverseHandleMapping[documentName][mirroredHandle];
                    System.Diagnostics.Debug.WriteLine($"镜像文档查询原始Handle: {mirroredHandle} -> {result}");
                    return result;
                }
            }
            else
            {
                // 原始文档：查询 镜像Handle -> 原始Handle 的映射
                if (_globalHandleMapping.ContainsKey(documentName) &&
                    _globalHandleMapping[documentName].ContainsKey(mirroredHandle))
                {
                    var result = _globalHandleMapping[documentName][mirroredHandle];
                    System.Diagnostics.Debug.WriteLine($"原始文档查询原始Handle: {mirroredHandle} -> {result}");
                    return result;
                }
            }
            
            return null;
        }
        
        /// <summary>
        /// 获取镜像实体
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="originalHandle">原始Handle</param>
        /// <returns>镜像实体，如果不存在则返回null</returns>
        public static EntityObject GetMirroredEntity(string documentName, string originalHandle)
        {
            if (string.IsNullOrEmpty(documentName) || string.IsNullOrEmpty(originalHandle))
                return null;
                
            if (_mirrorResults.ContainsKey(documentName) && 
                _mirrorResults[documentName].EntityMapping.ContainsKey(originalHandle))
            {
                return _mirrorResults[documentName].EntityMapping[originalHandle];
            }
            
            return null;
        }
        
        /// <summary>
        /// 检查是否为镜像实体
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="handle">实体Handle</param>
        /// <returns>是否为镜像实体</returns>
        public static bool IsMirroredEntity(string documentName, string handle)
        {
            if (string.IsNullOrEmpty(documentName) || string.IsNullOrEmpty(handle))
                return false;
                
            return _globalReverseHandleMapping.ContainsKey(documentName) && 
                   _globalReverseHandleMapping[documentName].ContainsKey(handle);
        }
        
        /// <summary>
        /// 获取镜像方向
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <returns>镜像方向</returns>
        public static MirrorDirection? GetMirrorDirection(string documentName)
        {
            if (string.IsNullOrEmpty(documentName) || !_mirrorResults.ContainsKey(documentName))
                return null;
                
            return _mirrorResults[documentName].Direction;
        }
        
        /// <summary>
        /// 获取镜像线信息
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <returns>镜像线信息</returns>
        public static MirrorLineInfo GetMirrorLine(string documentName)
        {
            if (string.IsNullOrEmpty(documentName) || !_mirrorResults.ContainsKey(documentName))
                return null;
                
            return _mirrorResults[documentName].MirrorLine;
        }
        
        /// <summary>
        /// 更新镜像实体
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="originalHandle">原始Handle</param>
        /// <param name="updatedEntity">更新后的镜像实体</param>
        public static void UpdateMirroredEntity(string documentName, string originalHandle, EntityObject updatedEntity)
        {
            if (string.IsNullOrEmpty(documentName) || string.IsNullOrEmpty(originalHandle) || updatedEntity == null)
                return;
                
            if (_mirrorResults.ContainsKey(documentName))
            {
                _mirrorResults[documentName].EntityMapping[originalHandle] = updatedEntity;
                System.Diagnostics.Debug.WriteLine($"镜像映射管理器: 更新实体 {documentName}:{originalHandle}");
            }
        }
        
        /// <summary>
        /// 删除镜像实体映射
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="originalHandle">原始Handle</param>
        public static void RemoveEntityMapping(string documentName, string originalHandle)
        {
            if (string.IsNullOrEmpty(documentName) || string.IsNullOrEmpty(originalHandle))
                return;
                
            if (_mirrorResults.ContainsKey(documentName))
            {
                var mirrorResult = _mirrorResults[documentName];
                
                // 获取镜像Handle
                string mirroredHandle = null;
                if (mirrorResult.HandleMapping.ContainsKey(originalHandle))
                {
                    mirroredHandle = mirrorResult.HandleMapping[originalHandle];
                }
                
                // 移除映射关系
                mirrorResult.HandleMapping.Remove(originalHandle);
                mirrorResult.EntityMapping.Remove(originalHandle);
                
                // 移除全局映射
                if (_globalHandleMapping.ContainsKey(documentName))
                    _globalHandleMapping[documentName].Remove(originalHandle);
                if (_globalReverseHandleMapping.ContainsKey(documentName) && mirroredHandle != null)
                    _globalReverseHandleMapping[documentName].Remove(mirroredHandle);
                    
                System.Diagnostics.Debug.WriteLine($"镜像映射管理器: 删除实体映射 {documentName}:{originalHandle}");
            }
        }
        
        /// <summary>
        /// 添加新的实体映射
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="originalHandle">原始Handle</param>
        /// <param name="mirroredHandle">镜像Handle</param>
        /// <param name="mirroredEntity">镜像实体</param>
        public static void AddEntityMapping(string documentName, string originalHandle, string mirroredHandle, EntityObject mirroredEntity)
        {
            if (string.IsNullOrEmpty(documentName) || string.IsNullOrEmpty(originalHandle) || 
                string.IsNullOrEmpty(mirroredHandle) || mirroredEntity == null)
                return;
                
            if (_mirrorResults.ContainsKey(documentName))
            {
                var mirrorResult = _mirrorResults[documentName];
                mirrorResult.HandleMapping[originalHandle] = mirroredHandle;
                mirrorResult.EntityMapping[originalHandle] = mirroredEntity;
                
                // 更新全局映射
                if (!_globalHandleMapping.ContainsKey(documentName))
                    _globalHandleMapping[documentName] = new Dictionary<string, string>();
                if (!_globalReverseHandleMapping.ContainsKey(documentName))
                    _globalReverseHandleMapping[documentName] = new Dictionary<string, string>();
                    
                _globalHandleMapping[documentName][originalHandle] = mirroredHandle;
                _globalReverseHandleMapping[documentName][mirroredHandle] = originalHandle;
                
                System.Diagnostics.Debug.WriteLine($"镜像映射管理器: 添加实体映射 {documentName}:{originalHandle} -> {mirroredHandle}");
            }
        }
        
        /// <summary>
        /// 获取文档的所有镜像映射信息
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <returns>镜像结果，如果不存在则返回null</returns>
        public static MirrorResult GetMirrorResult(string documentName)
        {
            if (string.IsNullOrEmpty(documentName) || !_mirrorResults.ContainsKey(documentName))
                return null;
                
            return _mirrorResults[documentName];
        }
        
        /// <summary>
        /// 清理文档的镜像映射信息
        /// </summary>
        /// <param name="documentName">文档名称</param>
        public static void ClearDocumentMapping(string documentName)
        {
            if (string.IsNullOrEmpty(documentName))
                return;
                
            _mirrorResults.Remove(documentName);
            _globalHandleMapping.Remove(documentName);
            _globalReverseHandleMapping.Remove(documentName);
            
            System.Diagnostics.Debug.WriteLine($"镜像映射管理器: 清理文档映射 {documentName}");
        }
        
        /// <summary>
        /// 获取所有已注册的文档名称
        /// </summary>
        /// <returns>文档名称列表</returns>
        public static List<string> GetRegisteredDocuments()
        {
            return _mirrorResults.Keys.ToList();
        }
        
        /// <summary>
        /// 获取映射统计信息
        /// </summary>
        /// <returns>映射统计信息</returns>
        public static Dictionary<string, int> GetMappingStatistics()
        {
            var stats = new Dictionary<string, int>();
            foreach (var kvp in _mirrorResults)
            {
                stats[kvp.Key] = kvp.Value.HandleMapping.Count;
            }
            return stats;
        }

        /// <summary>
        /// 获取指定文档的映射内容（用于调试）
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <returns>映射内容</returns>
        public static Dictionary<string, string> GetDocumentMappings(string documentName)
        {
            if (string.IsNullOrEmpty(documentName) || !_globalHandleMapping.ContainsKey(documentName))
                return new Dictionary<string, string>();
                
            return new Dictionary<string, string>(_globalHandleMapping[documentName]);
        }

        /// <summary>
        /// 获取指定文档的前几个映射示例（用于调试）
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="count">示例数量</param>
        /// <returns>映射示例</returns>
        public static List<string> GetMappingExamples(string documentName, int count = 5)
        {
            var examples = new List<string>();
            if (string.IsNullOrEmpty(documentName) || !_globalHandleMapping.ContainsKey(documentName))
                return examples;
                
            var mappings = _globalHandleMapping[documentName];
            int i = 0;
            foreach (var kvp in mappings)
            {
                if (i >= count) break;
                examples.Add($"{kvp.Key} -> {kvp.Value}");
                i++;
            }
            
            return examples;
        }
    }

    /// <summary>
    /// DXF镜像转换器，用于处理DXF文档的镜像操作
    /// </summary>
    public class DxfMirrorConverter
    {
        /// <summary>
        /// 执行镜像操作并返回映射关系
        /// </summary>
        /// <param name="sourceDocument">源DXF文档</param>
        /// <param name="direction">镜像方向</param>
        /// <returns>镜像结果，包含文档和映射关系</returns>
        public static MirrorResult MirrorWithMapping(DxfDocument sourceDocument, MirrorDirection direction, bool needSync = true)
        {
            if (sourceDocument == null)
                throw new ArgumentNullException(nameof(sourceDocument));

            var result = new MirrorResult
            {
                MirroredDocument = new DxfDocument(),
                Direction = direction,
                DocumentName = (sourceDocument.Name ?? $"Document_{Guid.NewGuid():N}" )+ "_Mirrored"
            };

            // 复制图层信息
            foreach (var layer in sourceDocument.Layers)
            {
                result.MirroredDocument.Layers.Add((Layer)layer.Clone());
            }

            var entityCollection = new EntityCollection();
            entityCollection.AddRange(sourceDocument.Entities.All);

            // 获取实体的边界框
            var boundingBox = GetBoundingBox(entityCollection);
            if (boundingBox == null)
                return result;

            // 计算镜像线
            var mirrorLine = GetMirrorLine(boundingBox, direction);
            result.MirrorLine = new MirrorLineInfo(mirrorLine.Start, mirrorLine.End, direction);

            // 镜像所有实体并建立映射关系
            var entities = sourceDocument.Entities.All.ToList();
            foreach (var entity in entities)
            {
                var mirroredEntity = MirrorEntity(entity, mirrorLine, !needSync);
                if (mirroredEntity != null)
                {
                    result.MirroredDocument.Entities.Add(mirroredEntity);
                    
                    // 建立 Handle 映射关系 - 修改这里，使用带前缀的实体ID
                    if (!string.IsNullOrEmpty(entity.Handle) && needSync)
                    {
                        // 根据实体类型生成带前缀的映射关系
                        string originalKey = GetEntityIdWithPrefix(entity);
                        string mirroredKey = GetEntityIdWithPrefix(mirroredEntity);
                        
                        if (!string.IsNullOrEmpty(originalKey) && !string.IsNullOrEmpty(mirroredKey))
                        {
                            result.HandleMapping[originalKey] = mirroredKey;
                            result.EntityMapping[originalKey] = mirroredEntity;
                            
                            System.Diagnostics.Debug.WriteLine($"建立Handle映射: {originalKey} -> {mirroredKey}");
                        }
                    }
                }
            }

            if(needSync) // 注册到全局映射管理器
                MirrorEntityMappingManager.RegisterMirrorResult(result.DocumentName, result);

            return result;
        }

        /// <summary>
        /// 根据镜像方向获取镜像位置
        /// </summary>
        /// <param name="originalPosition">原始位置</param>
        /// <param name="documentName">文档名称</param>
        /// <returns>镜像位置</returns>
        public static Vector2 GetMirroredPosition(Vector2 originalPosition, string documentName)
        {
            var mirrorLine = MirrorEntityMappingManager.GetMirrorLine(documentName);
            if (mirrorLine == null)
                return originalPosition;
                
            return MirrorPoint(originalPosition, (mirrorLine.StartPoint, mirrorLine.EndPoint));
        }

        /// <summary>
        /// 根据镜像方向获取镜像位置（Point3D版本）
        /// </summary>
        /// <param name="originalPosition">原始位置</param>
        /// <param name="documentName">文档名称</param>
        /// <returns>镜像位置</returns>
        public static Vector3 GetMirroredPosition(Vector3 originalPosition, string documentName)
        {
            var mirrorLine = MirrorEntityMappingManager.GetMirrorLine(documentName);
            if (mirrorLine == null)
                return originalPosition;
                
            var mirrored2D = MirrorPoint(new Vector2(originalPosition.X, originalPosition.Y), 
                                        (mirrorLine.StartPoint, mirrorLine.EndPoint));
            return new Vector3(mirrored2D.X, mirrored2D.Y, originalPosition.Z);
        }

        /// <summary>
        /// 根据镜像方向获取镜像角度
        /// </summary>
        /// <param name="originalRotation">原始角度</param>
        /// <param name="documentName">文档名称</param>
        /// <returns>镜像角度</returns>
        public static double GetMirroredRotation(double originalRotation, string documentName)
        {
            var direction = MirrorEntityMappingManager.GetMirrorDirection(documentName);
            if (!direction.HasValue)
                return originalRotation;
                
            // 镜像角度计算
            switch (direction.Value)
            {
                case MirrorDirection.Horizontal:
                    return 360 - originalRotation;
                case MirrorDirection.Vertical:
                    return 180 - originalRotation;
                default:
                    return originalRotation;
            }
        }

        /// <summary>
        /// 同步镜像实体的编辑操作
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="originalHandle">原始Handle</param>
        /// <param name="editOperation">编辑操作委托</param>
        /// <returns>操作是否成功</returns>
        public static bool SyncMirroredEntityEdit(string documentName, string originalHandle, Action<EntityObject> editOperation)
        {
            try
            {
                var mirroredEntity = MirrorEntityMappingManager.GetMirroredEntity(documentName, originalHandle);
                if (mirroredEntity == null)
                    return false;
                    
                // 执行编辑操作
                editOperation?.Invoke(mirroredEntity);
                
                // 更新映射管理器中的实体
                MirrorEntityMappingManager.UpdateMirroredEntity(documentName, originalHandle, mirroredEntity);
                
                System.Diagnostics.Debug.WriteLine($"镜像实体编辑同步成功: {documentName}:{originalHandle}");
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"镜像实体编辑同步失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 删除镜像实体
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="originalHandle">原始Handle</param>
        /// <returns>操作是否成功</returns>
        public static bool DeleteMirroredEntity(string documentName, string originalHandle)
        {
            try
            {
                var mirrorResult = MirrorEntityMappingManager.GetMirrorResult(documentName);
                if (mirrorResult?.MirroredDocument == null)
                    return false;
                    
                var mirroredEntity = MirrorEntityMappingManager.GetMirroredEntity(documentName, originalHandle);
                if (mirroredEntity == null)
                    return false;
                    
                // 从镜像文档中移除实体
                mirrorResult.MirroredDocument.Entities.Remove(mirroredEntity);
                
                // 从映射管理器中移除映射关系
                MirrorEntityMappingManager.RemoveEntityMapping(documentName, originalHandle);
                
                System.Diagnostics.Debug.WriteLine($"镜像实体删除成功: {documentName}:{originalHandle}");
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"镜像实体删除失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 添加新的镜像实体
        /// </summary>
        /// <param name="documentName">文档名称</param>
        /// <param name="originalHandle">原始Handle</param>
        /// <param name="newEntity">新实体</param>
        /// <returns>操作是否成功</returns>
        public static bool AddNewMirroredEntity(string documentName, string originalHandle, EntityObject newEntity)
        {
            try
            {
                var mirrorResult = MirrorEntityMappingManager.GetMirrorResult(documentName);
                if (mirrorResult?.MirroredDocument == null || newEntity == null)
                    return false;
                    
                // 添加到镜像文档
                mirrorResult.MirroredDocument.Entities.Add(newEntity);
                
                // 添加到映射管理器
                MirrorEntityMappingManager.AddEntityMapping(documentName, originalHandle, newEntity.Handle, newEntity);
                
                System.Diagnostics.Debug.WriteLine($"新镜像实体添加成功: {documentName}:{originalHandle}");
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"新镜像实体添加失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 获取实体的边界框
        /// </summary>
        private static BoundingBox GetBoundingBox(EntityCollection entities)
        {
            if (entities == null || entities.Count == 0)
                return null;

            double minX = double.MaxValue;
            double minY = double.MaxValue;
            double maxX = double.MinValue;
            double maxY = double.MinValue;

            var entityList = entities.ToList();
            foreach (var entity in entityList)
            {
                var box = GetEntityBoundingBox(entity);
                if (box != null)
                {
                    minX = Math.Min(minX, box.MinPoint.X);
                    minY = Math.Min(minY, box.MinPoint.Y);
                    maxX = Math.Max(maxX, box.MaxPoint.X);
                    maxY = Math.Max(maxY, box.MaxPoint.Y);
                }
            }

            if (minX == double.MaxValue || minY == double.MaxValue)
                return null;

            return new BoundingBox(
                new Vector2(minX, minY),
                new Vector2(maxX, maxY)
            );
        }

        /// <summary>
        /// 获取单个实体的边界框
        /// </summary>
        private static BoundingBox GetEntityBoundingBox(EntityObject entity)
        {
            if (entity == null)
                return null;

            switch (entity)
            {
                case Line line:
                    return new BoundingBox(
                        new Vector2(Math.Min(line.StartPoint.X, line.EndPoint.X), Math.Min(line.StartPoint.Y, line.EndPoint.Y)),
                        new Vector2(Math.Max(line.StartPoint.X, line.EndPoint.X), Math.Max(line.StartPoint.Y, line.EndPoint.Y))
                    );
                case Circle circle:
                    return new BoundingBox(
                        new Vector2(circle.Center.X - circle.Radius, circle.Center.Y - circle.Radius),
                        new Vector2(circle.Center.X + circle.Radius, circle.Center.Y + circle.Radius)
                    );
                case Arc arc:
                    // 计算圆弧的边界框
                    var points = new List<Vector2>();
                    points.Add(new Vector2(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngle * Math.PI / 180),
                                         arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngle * Math.PI / 180)));
                    points.Add(new Vector2(arc.Center.X + arc.Radius * Math.Cos(arc.EndAngle * Math.PI / 180),
                                         arc.Center.Y + arc.Radius * Math.Sin(arc.EndAngle * Math.PI / 180)));
                    return new BoundingBox(
                        new Vector2(points.Min(p => p.X), points.Min(p => p.Y)),
                        new Vector2(points.Max(p => p.X), points.Max(p => p.Y))
                    );
                case Polyline polyline:
                    var vertices = new List<Vector2>();
                    foreach (var vertex in polyline.Vertexes)
                    {
                        vertices.Add(new Vector2(vertex.Position.X, vertex.Position.Y));
                    }
                    return new BoundingBox(
                        new Vector2(vertices.Min(p => p.X), vertices.Min(p => p.Y)),
                        new Vector2(vertices.Max(p => p.X), vertices.Max(p => p.Y))
                    );
                default:
                    return null;
            }
        }

        /// <summary>
        /// 获取镜像线
        /// </summary>
        private static (Vector2 Start, Vector2 End) GetMirrorLine(BoundingBox boundingBox, MirrorDirection direction)
        {
            if (direction == MirrorDirection.Horizontal)
            {
                // 水平镜像线（垂直直线）
                double x = (boundingBox.MinPoint.X + boundingBox.MaxPoint.X) / 2;
                return (
                    new Vector2(x, boundingBox.MinPoint.Y),
                    new Vector2(x, boundingBox.MaxPoint.Y)
                );
            }
            else
            {
                // 垂直镜像线（水平直线）
                double y = (boundingBox.MinPoint.Y + boundingBox.MaxPoint.Y) / 2;
                return (
                    new Vector2(boundingBox.MinPoint.X, y),
                    new Vector2(boundingBox.MaxPoint.X, y)
                );
            }
        }

        /// <summary>
        /// 镜像单个实体
        /// </summary>
        private static EntityObject MirrorEntity(EntityObject entity, (Vector2 Start, Vector2 End) mirrorLine, bool bMirrorText = false)
        {
            if (entity == null)
                return null;

            // 创建实体的副本
            var mirroredEntity = (EntityObject)entity.Clone();

            // 根据实体类型执行镜像
            switch (entity)
            {
                case Line line:
                    MirrorLine((Line)mirroredEntity, mirrorLine);
                    break;
                case Circle circle:
                    MirrorCircle((Circle)mirroredEntity, mirrorLine);
                    break;
                case Arc arc:
                    MirrorArc((Arc)mirroredEntity, mirrorLine);
                    break;
                case Polyline polyline:
                    MirrorPolyline((Polyline)mirroredEntity, mirrorLine);
                    break;
                case Text text:
                    if(bMirrorText)//HelixTook3D中滞后镜像默认不镜像文本
                        MirrorText((Text)mirroredEntity, mirrorLine);
                    break;
                case MText mtext:
                    if (bMirrorText)//HelixTook3D中滞后镜像默认不镜像文本
                        MirrorMText((MText)mirroredEntity, mirrorLine);
                    break;
                // 可以添加更多实体类型的处理
            }

            return mirroredEntity;
        }

        /// <summary>
        /// 镜像点
        /// </summary>
        private static Vector2 MirrorPoint(Vector2 point, (Vector2 Start, Vector2 End) mirrorLine)
        {
            // 计算点到镜像线的向量
            var lineVector = mirrorLine.End - mirrorLine.Start;
            var pointVector = point - mirrorLine.Start;

            // Fix for CS1061: Replace the usage of `LengthSquared` with the correct calculation for the squared length of a vector.  
            // Since `Vector2` does not have a `LengthSquared` property or method, we can calculate it manually using the formula: X^2 + Y^2.

            var projection = Vector2.DotProduct(pointVector, lineVector) / (lineVector.X * lineVector.X + lineVector.Y * lineVector.Y);
            var projectedPoint = mirrorLine.Start + lineVector * projection;

            // 计算镜像点
            return point + 2 * (projectedPoint - point);
        }

        /// <summary>
        /// 镜像直线
        /// </summary>
        private static void MirrorLine(Line line, (Vector2 Start, Vector2 End) mirrorLine)
        {
            var startPoint = MirrorPoint(new Vector2(line.StartPoint.X, line.StartPoint.Y), mirrorLine);
            var endPoint = MirrorPoint(new Vector2(line.EndPoint.X, line.EndPoint.Y), mirrorLine);
            line.StartPoint = new Vector3(startPoint.X, startPoint.Y, line.StartPoint.Z);
            line.EndPoint = new Vector3(endPoint.X, endPoint.Y, line.EndPoint.Z);
        }

        /// <summary>
        /// 镜像圆
        /// </summary>
        private static void MirrorCircle(Circle circle, (Vector2 Start, Vector2 End) mirrorLine)
        {
            var center = MirrorPoint(new Vector2(circle.Center.X, circle.Center.Y), mirrorLine);
            circle.Center = new Vector3(center.X, center.Y, circle.Center.Z);
        }

        /// <summary>
        /// 镜像圆弧
        /// </summary>
        private static void MirrorArc(Arc arc, (Vector2 Start, Vector2 End) mirrorLine)
        {
            // 镜像圆心
            var center = MirrorPoint(new Vector2(arc.Center.X, arc.Center.Y), mirrorLine);
            arc.Center = new Vector3(center.X, center.Y, arc.Center.Z);

            // 计算原始角度差
            double originalAngleDiff = arc.EndAngle - arc.StartAngle;
            if (originalAngleDiff < 0)
            {
                originalAngleDiff += 360;
            }

            // 镜像角度
            double newStartAngle = 360 - arc.EndAngle;
            double newEndAngle = 360 - arc.StartAngle;

            // 保持原始圆弧的大小和方向
            if (originalAngleDiff > 180)
            {
                // 原始是优弧，保持为优弧
                if (newEndAngle < newStartAngle)
                {
                    newEndAngle += 360;
                }
            }
            else
            {
                // 原始是劣弧，保持为劣弧
                if (newEndAngle > newStartAngle)
                {
                    newEndAngle -= 360;
                }
            }

            arc.StartAngle = newStartAngle;
            arc.EndAngle = newEndAngle;

            // 根据镜像线方向调整法向量
            if (mirrorLine.Start.X == mirrorLine.End.X) // 垂直镜像线
            {
                arc.Normal = new Vector3(-arc.Normal.X, arc.Normal.Y, arc.Normal.Z);
            }
            else // 水平镜像线
            {
                arc.Normal = new Vector3(arc.Normal.X, -arc.Normal.Y, arc.Normal.Z);
            }
        }

        /// <summary>
        /// 镜像多段线
        /// </summary>
        private static void MirrorPolyline(Polyline polyline, (Vector2 Start, Vector2 End) mirrorLine)
        {
            var vertices = new List<MLineVertex>();
            foreach (var vertex in polyline.Vertexes)
            {
                var mirroredPoint = MirrorPoint(new Vector2(vertex.Position.X, vertex.Position.Y), mirrorLine);
                var newVertex = (MLineVertex)vertex.Clone(); // Clone the existing vertex  
                newVertex.Position = mirroredPoint; // Update the position with the mirrored point  
                vertices.Add(newVertex);
            }
            polyline.Vertexes.Clear();
            polyline.Vertexes.AddRange(vertices);
        }

        /// <summary>
        /// 镜像文本
        /// </summary>
        public static void MirrorText(Text text, (Vector2 Start, Vector2 End) mirrorLine)
        {
            // 镜像文本位置
            var position = MirrorPoint(new Vector2(text.Position.X, text.Position.Y), mirrorLine);
            text.Position = new Vector3(position.X, position.Y, text.Position.Z);

            // 镜像文本方向
            text.Rotation = 360 - text.Rotation;

            // 根据镜像方向调整对齐方式
            if (mirrorLine.Start.X == mirrorLine.End.X) // 垂直镜像线
            {
                switch (text.Alignment)
                {
                    case TextAlignment.TopLeft:
                        text.Alignment = TextAlignment.TopRight;
                        break;
                    case TextAlignment.TopCenter:
                        text.Alignment = TextAlignment.TopCenter;
                        break;
                    case TextAlignment.TopRight:
                        text.Alignment = TextAlignment.TopLeft;
                        break;
                    case TextAlignment.MiddleLeft:
                        text.Alignment = TextAlignment.MiddleRight;
                        break;
                    case TextAlignment.MiddleCenter:
                        text.Alignment = TextAlignment.MiddleCenter;
                        break;
                    case TextAlignment.MiddleRight:
                        text.Alignment = TextAlignment.MiddleLeft;
                        break;
                    case TextAlignment.BottomLeft:
                        text.Alignment = TextAlignment.BottomRight;
                        break;
                    case TextAlignment.BottomCenter:
                        text.Alignment = TextAlignment.BottomCenter;
                        break;
                    case TextAlignment.BottomRight:
                        text.Alignment = TextAlignment.BottomLeft;
                        break;
                }
            }
            else // 水平镜像线
            {
                switch (text.Alignment)
                {
                    case TextAlignment.TopLeft:
                        text.Alignment = TextAlignment.BottomLeft;
                        break;
                    case TextAlignment.TopCenter:
                        text.Alignment = TextAlignment.BottomCenter;
                        break;
                    case TextAlignment.TopRight:
                        text.Alignment = TextAlignment.BottomRight;
                        break;
                    case TextAlignment.MiddleLeft:
                        text.Alignment = TextAlignment.MiddleLeft;
                        break;
                    case TextAlignment.MiddleCenter:
                        text.Alignment = TextAlignment.MiddleCenter;
                        break;
                    case TextAlignment.MiddleRight:
                        text.Alignment = TextAlignment.MiddleRight;
                        break;
                    case TextAlignment.BottomLeft:
                        text.Alignment = TextAlignment.TopLeft;
                        break;
                    case TextAlignment.BottomCenter:
                        text.Alignment = TextAlignment.TopCenter;
                        break;
                    case TextAlignment.BottomRight:
                        text.Alignment = TextAlignment.TopRight;
                        break;
                }
            }
        }

        /// <summary>
        /// 镜像多行文本
        /// </summary>
        private static void MirrorMText(MText mtext, (Vector2 Start, Vector2 End) mirrorLine)
        {
            // 镜像文本位置
            var position = MirrorPoint(new Vector2(mtext.Position.X, mtext.Position.Y), mirrorLine);
            mtext.Position = new Vector3(position.X, position.Y, mtext.Position.Z);

            // 镜像文本方向
            mtext.Rotation = 360 - mtext.Rotation;

            // 根据镜像方向调整对齐方式
            if (mirrorLine.Start.X == mirrorLine.End.X) // 垂直镜像线
            {
                switch (mtext.AttachmentPoint)
                {
                    case MTextAttachmentPoint.TopLeft:
                        mtext.AttachmentPoint = MTextAttachmentPoint.TopRight;
                        break;
                    case MTextAttachmentPoint.TopCenter:
                        mtext.AttachmentPoint = MTextAttachmentPoint.TopCenter;
                        break;
                    case MTextAttachmentPoint.TopRight:
                        mtext.AttachmentPoint = MTextAttachmentPoint.TopLeft;
                        break;
                    case MTextAttachmentPoint.MiddleLeft:
                        mtext.AttachmentPoint = MTextAttachmentPoint.MiddleRight;
                        break;
                    case MTextAttachmentPoint.MiddleCenter:
                        mtext.AttachmentPoint = MTextAttachmentPoint.MiddleCenter;
                        break;
                    case MTextAttachmentPoint.MiddleRight:
                        mtext.AttachmentPoint = MTextAttachmentPoint.MiddleLeft;
                        break;
                    case MTextAttachmentPoint.BottomLeft:
                        mtext.AttachmentPoint = MTextAttachmentPoint.BottomRight;
                        break;
                    case MTextAttachmentPoint.BottomCenter:
                        mtext.AttachmentPoint = MTextAttachmentPoint.BottomCenter;
                        break;
                    case MTextAttachmentPoint.BottomRight:
                        mtext.AttachmentPoint = MTextAttachmentPoint.BottomLeft;
                        break;
                }
            }
            else // 水平镜像线
            {
                switch (mtext.AttachmentPoint)
                {
                    case MTextAttachmentPoint.TopLeft:
                        mtext.AttachmentPoint = MTextAttachmentPoint.BottomLeft;
                        break;
                    case MTextAttachmentPoint.TopCenter:
                        mtext.AttachmentPoint = MTextAttachmentPoint.BottomCenter;
                        break;
                    case MTextAttachmentPoint.TopRight:
                        mtext.AttachmentPoint = MTextAttachmentPoint.BottomRight;
                        break;
                    case MTextAttachmentPoint.MiddleLeft:
                        mtext.AttachmentPoint = MTextAttachmentPoint.MiddleLeft;
                        break;
                    case MTextAttachmentPoint.MiddleCenter:
                        mtext.AttachmentPoint = MTextAttachmentPoint.MiddleCenter;
                        break;
                    case MTextAttachmentPoint.MiddleRight:
                        mtext.AttachmentPoint = MTextAttachmentPoint.MiddleRight;
                        break;
                    case MTextAttachmentPoint.BottomLeft:
                        mtext.AttachmentPoint = MTextAttachmentPoint.TopLeft;
                        break;
                    case MTextAttachmentPoint.BottomCenter:
                        mtext.AttachmentPoint = MTextAttachmentPoint.TopCenter;
                        break;
                    case MTextAttachmentPoint.BottomRight:
                        mtext.AttachmentPoint = MTextAttachmentPoint.TopRight;
                        break;
                }
            }
        }

        /// <summary>
        /// 根据实体类型生成带前缀的实体ID
        /// </summary>
        /// <param name="entity">DXF实体</param>
        /// <returns>带前缀的实体ID</returns>
        private static string GetEntityIdWithPrefix(EntityObject entity)
        {
            if (entity == null || string.IsNullOrEmpty(entity.Handle))
                return null;
                
            switch (entity)
            {
                case Text text:
                    return $"Text_{entity.Handle}";
                case MText mText:
                    return $"MText_{entity.Handle}";
                case Line line:
                    return $"Line_{entity.Handle}";
                case Circle circle:
                    return $"Circle_{entity.Handle}";
                case Arc arc:
                    return $"Arc_{entity.Handle}";
                default:
                    return entity.Handle; // 其他类型保持原样
            }
        }
    }

    /// <summary>
    /// 边界框类，用于表示实体的边界
    /// </summary>
    public class BoundingBox
    {
        public Vector2 MinPoint { get; }
        public Vector2 MaxPoint { get; }

        public BoundingBox(Vector2 minPoint, Vector2 maxPoint)
        {
            MinPoint = minPoint;
            MaxPoint = maxPoint;
        }
    }
} 